<template>
  <div class="feedback-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>用户反馈管理</span>
          <el-button-group>
            <el-button type="primary" @click="handleBatchReply"
              >批量回复</el-button
            >
            <el-button type="success" @click="exportData">导出数据</el-button>
          </el-button-group>
        </div>
      </template>

      <!-- 搜索栏 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="反馈类型">
          <el-select
            v-model="searchForm.feedbackType"
            placeholder="请选择反馈类型"
          >
            <el-option label="功能建议" value="feature" />
            <el-option label="体验问题" value="experience" />
            <el-option label="系统故障" value="bug" />
            <el-option label="其他" value="others" />
          </el-select>
        </el-form-item>
        <el-form-item label="处理状态">
          <el-select v-model="searchForm.status" placeholder="请选择处理状态">
            <el-option label="待处理" value="pending" />
            <el-option label="已回复" value="replied" />
            <el-option label="已关闭" value="closed" />
          </el-select>
        </el-form-item>
        <el-form-item label="提交时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="sortedFeedbackList"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        @sort-change="handleSortChange"
      >
        <template #empty>
          <div class="empty-state">
            <el-empty 
              description="暂无反馈数据" 
              :image-size="200"
            >
              <div class="empty-text">还没有收到任何用户反馈</div>
              <div class="empty-subtext">用户反馈将在这里显示，您可以及时回复处理</div>
            </el-empty>
          </div>
        </template>
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="反馈ID" width="120" />
        <el-table-column label="用户信息" min-width="200">
          <template #default="{ row }">
            <div class="user-info">
              <el-avatar :size="40" :src="row.userAvatar" />
              <div class="info-content">
                <div class="username">{{ row.username }}</div>
                <div class="user-contact">{{ row.userContact }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="反馈类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getFeedbackTypeTag(row.type)">
              {{ getFeedbackTypeLabel(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="content"
          label="反馈内容"
          min-width="200"
          show-overflow-tooltip
        />
        <el-table-column
          prop="createTime"
          label="提交时间"
          width="160"
          sortable="custom"
        />
        <el-table-column prop="status" label="处理状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTag(row.status)">
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="priority"
          label="优先级"
          width="100"
          sortable="custom"
        >
          <template #default="{ row }">
            <el-tag :type="getPriorityTag(row.priority)">
              {{ getPriorityLabel(row.priority) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button
                type="primary"
                size="small"
                :disabled="row.status === 'closed'"
                @click="handleReply(row)"
              >
                回复
              </el-button>
              <el-button type="info" size="small" @click="viewDetail(row)">
                详情
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 回复对话框 -->
    <el-dialog
      v-model="replyDialogVisible"
      title="回复反馈"
      width="600px"
      :modal="true"
      :lock-scroll="true"
      :close-on-click-modal="false"
      modal-class="feedback-modal"
      destroy-on-close
      class="feedback-dialog"
    >
      <div class="reply-form">
        <el-form
          ref="formRef"
          :model="replyForm"
          :rules="replyRules"
          label-width="100px"
        >
          <el-form-item label="反馈内容" class="feedback-content">
            <div class="content-box">{{ currentFeedback.content }}</div>
          </el-form-item>
          <el-form-item label="处理结果" prop="result">
            <el-radio-group v-model="replyForm.result">
              <el-radio label="replied">回复处理</el-radio>
              <el-radio label="closed">关闭反馈</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="回复内容" prop="content">
            <el-input
              v-model="replyForm.content"
              type="textarea"
              :rows="4"
              placeholder="请输入回复内容"
            />
          </el-form-item>
          <el-form-item label="处理优先级" prop="priority">
            <el-select v-model="replyForm.priority" placeholder="请选择优先级">
              <el-option label="高" value="high" />
              <el-option label="中" value="medium" />
              <el-option label="低" value="low" />
            </el-select>
          </el-form-item>
          <el-form-item label="上传附件">
            <el-upload
              action="/api/admin/upload"
              list-type="picture-card"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :before-remove="beforeRemove"
              multiple
            >
              <el-icon><Plus /></el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item label="通知用户">
            <el-switch v-model="replyForm.notifyUser" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="replyDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitReply">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="反馈详情"
      width="800px"
      :modal="true"
      :lock-scroll="true"
      :close-on-click-modal="false"
      modal-class="feedback-modal"
      destroy-on-close
      class="feedback-dialog"
    >
      <div class="detail-content">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="反馈ID">{{
            currentFeedback.id
          }}</el-descriptions-item>
          <el-descriptions-item label="提交时间">{{
            currentFeedback.createTime
          }}</el-descriptions-item>
          <el-descriptions-item label="反馈类型">
            <el-tag :type="getFeedbackTypeTag(currentFeedback.type)">
              {{ getFeedbackTypeLabel(currentFeedback.type) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="处理状态">
            <el-tag :type="getStatusTag(currentFeedback.status)">
              {{ getStatusLabel(currentFeedback.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="反馈内容" :span="2">
            {{ currentFeedback.content }}
          </el-descriptions-item>
          <el-descriptions-item
            label="反馈图片"
            :span="2"
            v-if="currentFeedback.images?.length"
          >
            <div class="feedback-images">
              <el-image
                v-for="(url, index) in currentFeedback.images"
                :key="index"
                :src="url"
                :preview-src-list="currentFeedback.images"
                fit="cover"
                class="feedback-image"
              />
            </div>
          </el-descriptions-item>
        </el-descriptions>

        <div class="reply-history mt-4">
          <h4>回复记录</h4>
          <el-timeline>
            <el-timeline-item
              v-for="(reply, index) in currentFeedback.replyHistory"
              :key="index"
              :timestamp="reply.time"
              :type="reply.type"
            >
              <h4>{{ reply.title }}</h4>
              <p>{{ reply.content }}</p>
              <div v-if="reply.attachments?.length" class="reply-attachments">
                <el-image
                  v-for="(url, aIndex) in reply.attachments"
                  :key="aIndex"
                  :src="url"
                  :preview-src-list="reply.attachments"
                  fit="cover"
                  class="attachment-image"
                />
              </div>
            </el-timeline-item>
          </el-timeline>
        </div>

        <div class="user-info mt-4">
          <h4>用户信息</h4>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="用户名">{{
              currentFeedback.username
            }}</el-descriptions-item>
            <el-descriptions-item label="联系方式">{{
              currentFeedback.userContact
            }}</el-descriptions-item>
            <el-descriptions-item label="注册时间">{{
              currentFeedback.userRegTime
            }}</el-descriptions-item>
            <el-descriptions-item label="反馈次数">{{
              currentFeedback.feedbackCount
            }}</el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import service from "@/api/axios";
import * as XLSX from 'xlsx';

// API接口
const API = {
  getFeedbackList: (params) => service.get('/admin/feedback', { params }),
  getFeedbackDetail: (id) => service.get(`/admin/feedback/${id}`),
  replyFeedback: (id, data) => service.post(`/admin/feedback/${id}/reply`, data),
  batchReplyFeedback: (data) => service.post('/admin/feedback/batch-reply', data),
  changeFeedbackStatus: (id, data) => service.put(`/admin/feedback/${id}/status`, data)
};

// 搜索表单
const searchForm = reactive({
  feedbackType: "",
  status: "",
  dateRange: [],
});

// 表格数据
const loading = ref(false);
const feedbackList = ref([]);

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 回复对话框
const replyDialogVisible = ref(false);
const formRef = ref(null);
const replyForm = reactive({
  result: "replied",
  content: "",
  priority: "medium",
  notifyUser: true,
});

// 回复表单验证规则
const replyRules = {
  result: [{ required: true, message: "请选择处理结果", trigger: "change" }],
  content: [{ required: true, message: "请输入回复内容", trigger: "blur" }],
  priority: [{ required: true, message: "请选择优先级", trigger: "change" }],
};

// 详情对话框
const detailDialogVisible = ref(false);
const currentFeedback = ref({});

// 排序相关
const sortConfig = reactive({
  prop: "",
  order: "",
});

// 获取反馈类型标签
const getFeedbackTypeLabel = (type) => {
  const types = {
    feature: "功能建议",
    experience: "体验问题",
    bug: "系统故障",
    others: "其他",
  };
  return types[type] || type;
};

// 获取反馈类型标签样式
const getFeedbackTypeTag = (type) => {
  const types = {
    feature: "success",
    experience: "warning",
    bug: "danger",
    others: "info",
  };
  return types[type] || "";
};

// 获取状态标签
const getStatusLabel = (status) => {
  const statuses = {
    pending: "待处理",
    replied: "已回复",
    closed: "已关闭",
  };
  return statuses[status] || status;
};

// 获取状态标签样式
const getStatusTag = (status) => {
  const statuses = {
    pending: "warning",
    replied: "success",
    closed: "info",
  };
  return statuses[status] || "";
};

// 获取优先级标签
const getPriorityLabel = (priority) => {
  const priorities = {
    high: "高",
    medium: "中",
    low: "低",
  };
  return priorities[priority] || priority;
};

// 获取优先级标签样式
const getPriorityTag = (priority) => {
  const priorities = {
    high: "danger",
    medium: "warning",
    low: "info",
  };
  return priorities[priority] || "";
};

// 搜索
const handleSearch = async () => {
  loading.value = true;
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      type: searchForm.feedbackType,
      status: searchForm.status,
      startTime: searchForm.dateRange?.[0],
      endTime: searchForm.dateRange?.[1],
      sortBy: sortConfig.prop,
      sortOrder: sortConfig.order,
    };

    try {
      const res = await API.getFeedbackList(params);
      feedbackList.value = res.list || [];
      total.value = res.total || 0;
    } catch (error) {
      console.error("API请求失败，使用测试数据", error);
      // 使用测试数据
      feedbackList.value = [
        {
          id: "FB202403150001",
          username: "张三",
          userAvatar: "https://example.com/avatar1.jpg",
          userContact: "13800138000",
          type: "feature",
          content: "建议增加更多的景点推荐功能，方便游客规划行程。",
          createTime: "2024-03-15 09:30:00",
          status: "pending",
          priority: "high",
          images: [
            "https://example.com/feedback1-1.jpg",
            "https://example.com/feedback1-2.jpg",
          ],
          userRegTime: "2023-12-01",
          feedbackCount: 3,
          replyHistory: [],
        },
        {
          id: "FB202403150002",
          username: "李四",
          userAvatar: "https://example.com/avatar2.jpg",
          userContact: "13800138001",
          type: "bug",
          content: "手机端预订门票时提交订单失败，但是显示扣款成功了。",
          createTime: "2024-03-15 10:15:00",
          status: "replied",
          priority: "high",
          images: ["https://example.com/feedback2-1.jpg"],
          userRegTime: "2024-01-15",
          feedbackCount: 1,
          replyHistory: [
            {
              time: "2024-03-15 10:30:00",
              title: "客服回复",
              content:
                "您好，已经为您查询到订单信息，款项将在1-3个工作日内退回您的支付账户。",
              type: "primary",
              operator: "王客服",
            },
          ],
        },
      ];
      total.value = 2;
    }
  } catch (error) {
    console.error("搜索失败：", error);
    ElMessage.error("搜索失败");
  } finally {
    loading.value = false;
  }
};

// 页面加载时获取数据
onMounted(() => {
  handleSearch();
});

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach((key) => {
    searchForm[key] = "";
  });
  searchForm.dateRange = [];
  handleSearch();
};

// 处理选择变化
const selectedFeedbacks = ref([]);
const handleSelectionChange = (val) => {
  selectedFeedbacks.value = val;
};

// 批量回复
const handleBatchReply = () => {
  if (selectedFeedbacks.value.length === 0) {
    ElMessage.warning("请选择要回复的反馈");
    return;
  }

  // 确认批量回复
  ElMessageBox.confirm(`确定要批量回复选中的${selectedFeedbacks.value.length}条反馈吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const ids = selectedFeedbacks.value.map(item => item.id);
      await API.batchReplyFeedback({
        ids,
        content: "感谢您的反馈，我们已收到并会尽快处理。",
        result: "replied",
        notifyUser: true
      });
      ElMessage.success("批量回复成功");
      handleSearch();
    } catch (error) {
      console.error("批量回复失败", error);
      ElMessage.error("批量回复失败");
    }
  }).catch(() => {});
};

// 导出数据
const exportData = () => {
  try {
    // 准备要导出的数据
    const exportData = feedbackList.value.map(feedback => ({
      '反馈ID': feedback.id,
      '用户名': feedback.username,
      '联系方式': feedback.userContact,
      '反馈类型': getFeedbackTypeLabel(feedback.type),
      '反馈内容': feedback.content,
      '提交时间': feedback.createTime,
      '处理状态': getStatusLabel(feedback.status),
      '优先级': getPriorityLabel(feedback.priority)
    }));

    // 创建工作簿
    const wb = XLSX.utils.book_new();
    // 将数据转换为工作表
    const ws = XLSX.utils.json_to_sheet(exportData);
    // 将工作表添加到工作簿
    XLSX.utils.book_append_sheet(wb, ws, '用户反馈');
    // 生成Excel文件并下载
    XLSX.writeFile(wb, `用户反馈_${new Date().toISOString().split('T')[0]}.xlsx`);
    
    ElMessage.success("数据导出成功");
  } catch (error) {
    console.error("导出数据失败", error);
    ElMessage.error("数据导出失败");
  }
};

// 回复反馈
const handleReply = async (row) => {
  try {
    // 尝试获取最新的反馈详情
    const detailData = await API.getFeedbackDetail(row.id);
    currentFeedback.value = detailData;
  } catch (error) {
    console.error("获取反馈详情失败，使用表格中的数据", error);
    currentFeedback.value = row;
  }
  
  replyForm.result = "replied";
  replyForm.content = "";
  replyForm.priority = row.priority;
  replyForm.notifyUser = true;
  replyDialogVisible.value = true;
};

// 查看详情
const viewDetail = async (row) => {
  try {
    // 尝试获取完整的反馈详情
    const detailData = await API.getFeedbackDetail(row.id);
    currentFeedback.value = detailData;
  } catch (error) {
    console.error("获取反馈详情失败，使用表格中的数据", error);
    currentFeedback.value = row;
  }
  
  detailDialogVisible.value = true;
};

// 提交回复
const submitReply = () => {
  formRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        await API.replyFeedback(currentFeedback.value.id, {
          content: replyForm.content,
          result: replyForm.result,
          priority: replyForm.priority,
          notifyUser: replyForm.notifyUser
        });
        
        ElMessage.success("回复成功");
        replyDialogVisible.value = false;
        handleSearch();
      } catch (error) {
        console.error("回复失败：", error);
        ElMessage.error("回复失败");
      }
    }
  });
};

// 文件上传相关方法
const handlePreview = (file) => {
  // 实现文件预览逻辑
  window.open(URL.createObjectURL(file.raw));
};

const handleRemove = (file, fileList) => {
  // 实现文件移除逻辑
  console.log("移除文件", file);
};

const beforeRemove = (file, fileList) => {
  return ElMessageBox.confirm(`确定移除 ${file.name}？`);
};

// 分页相关方法
const handleSizeChange = (val) => {
  pageSize.value = val;
  handleSearch();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  handleSearch();
};

// 处理排序变化
const handleSortChange = ({ prop, order }) => {
  sortConfig.prop = prop;
  sortConfig.order = order;
  handleSearch();
};

// 获取排序后的数据
const sortedFeedbackList = computed(() => {
  const list = [...feedbackList.value];
  if (!sortConfig.prop) return list;

  return list.sort((a, b) => {
    let aValue = a[sortConfig.prop];
    let bValue = b[sortConfig.prop];

    // 处理优先级排序
    if (sortConfig.prop === "priority") {
      const priorityOrder = { high: 3, medium: 2, low: 1 };
      aValue = priorityOrder[aValue] || 0;
      bValue = priorityOrder[bValue] || 0;
    }

    // 处理时间排序
    if (sortConfig.prop === "createTime") {
      aValue = new Date(aValue).getTime();
      bValue = new Date(bValue).getTime();
    }

    if (sortConfig.order === "ascending") {
      return aValue > bValue ? 1 : -1;
    } else {
      return aValue < bValue ? 1 : -1;
    }
  });
});
</script>

<style lang="scss" scoped>
:deep(.feedback-modal) {
  background-color: rgba(0, 0, 0, 0.5);
  backdrop-filter: blur(4px);
}

.feedback-management {
  padding: 20px;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .search-form {
    margin-bottom: 20px;
  }

  .user-info {
    display: flex;
    align-items: center;
    gap: 12px;

    .info-content {
      .username {
        font-weight: 500;
        margin-bottom: 4px;
      }

      .user-contact {
        font-size: 12px;
        color: var(--el-text-color-secondary);
      }
    }
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  .empty-state {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
  }

  .empty-text {
    margin-bottom: 10px;
    font-size: 16px;
    font-weight: bold;
  }

  .empty-subtext {
    margin-bottom: 20px;
    font-size: 14px;
    color: #909399;
  }

  .mt-4 {
    margin-top: 16px;
  }

  .feedback-dialog {
    :deep(.el-dialog__body) {
      padding: 0;
      overflow: hidden;
    }

    :deep(.el-dialog) {
      display: flex;
      flex-direction: column;
      max-height: 90vh;
      margin: 0 !important;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }

    :deep(.el-dialog__header) {
      padding: 20px;
      margin: 0;
      border-bottom: 1px solid var(--el-border-color-lighter);
    }

    :deep(.el-dialog__body) {
      flex: 1;
      overflow: hidden;
      padding: 0;
    }

    :deep(.el-dialog__footer) {
      padding: 20px;
      border-top: 1px solid var(--el-border-color-lighter);
    }

    .reply-form,
    .detail-content {
      height: 100%;
      padding: 20px;
      overflow-y: auto;
      box-sizing: border-box;

      &::-webkit-scrollbar {
        width: 6px;
      }

      &::-webkit-scrollbar-thumb {
        background-color: var(--el-border-color);
        border-radius: 3px;
      }

      &::-webkit-scrollbar-track {
        background-color: transparent;
      }
    }

    .feedback-content {
      .content-box {
        padding: 12px;
        background-color: var(--el-fill-color-lighter);
        border-radius: 4px;
        margin-bottom: 16px;
      }
    }

    .feedback-images,
    .reply-attachments {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
      margin: 8px 0;

      .feedback-image,
      .attachment-image {
        width: 100px;
        height: 100px;
        border-radius: 4px;
        object-fit: cover;
      }
    }

    .reply-history,
    .user-info {
      h4 {
        margin: 0 0 16px;
        font-size: 16px;
        color: var(--el-text-color-primary);
      }
    }

    .mt-4 {
      margin-top: 20px;
    }
  }
}
</style>
